package com.example.controller;

import com.example.model.Student;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 基于MySQL事务的例子
 * 基于RESTful 的例子
 * 基于MVC四类标签的例子
 */
@RestController
public class Ninth {

    @Autowired
    private StudentService studentService;

    /**
     * RESTful 查询使用
     * @param “detail” 是描述
     * @param “id” Select ID
     * @return Student
     */
    @ResponseBody
    @GetMapping("/selectStudent/detail/{id}")
    public Student selectStudent(@PathVariable("id") Integer id){
        Student resultStudent=studentService.selectStudent(id);
        return resultStudent;
    }

    /**
     *
     * insert增加用户
     * @param name
     * @return
     */
    @PostMapping("/insertStudent/detail/{name}/{age}")
    public Boolean insertStudent(
                                 @PathVariable("name") String name,
                                 @PathVariable("age") Integer age) {
        Student student = new Student( name, age);
        if (studentService.addStudent(student)==1){
          return true;
        }else {
            return false;
        }
    }

    /**
     *
     * 修改用户
     * @param name
     * @return
     */
    @PutMapping("/upStudent/detail/{id}/{name}/{age}")
    public Boolean updateStudent(@PathVariable("id") Integer id,
                                 @PathVariable("name") String name,
                                 @PathVariable("age") Integer age){
        Student student = new Student(id, name, age);
        Boolean aBoolean = studentService.updateStudent(student);
        return aBoolean;
    }

    /**
     * 事务回滚  在service方法里面  有@Transactional标签  若方法失败则事务回滚
     * 不整个controller进行事务是为了效率
     * @return
     */
    @RequestMapping(value = "/transacational/modify")
    public @ResponseBody Object transactionalStudentById() {
        int count = 0;
        try {
            Student student = new Student();
            student.setId(1);
            student.setName("Jack36");
            student.setAge(36);
            count = studentService.transactionalStudentById(student);
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
        return count;
    }


    @DeleteMapping("/student/del/{id}")
    public @ResponseBody Boolean deleteStudentById(@PathVariable("id") Integer id){
        Boolean aBoolean = studentService.deleteById(id);
        return aBoolean;
    }
}
